package com.imooc.service.impl;

import com.imooc.mapper.DbStuMapper;
import com.imooc.mapper.DbStuMapperCustom;
import com.imooc.pojo.DbStu;
import com.imooc.service.StuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.UUID;

@Service
public class StuServiceImpl implements StuService {
    @Autowired
    private DbStuMapper dbStuMapper;
    @Autowired
    private DbStuMapperCustom stuMapperCustom;  // 自定义mapper
    @Override
    public void saveStu(DbStu stu) {
        dbStuMapper.insert(stu);
    }
    @Override
    public DbStu queryByIdCustom(String id) {
        List<DbStu> list = stuMapperCustom.getStuById(id);
        if(list != null && !list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }
    @Override
    public DbStu queryById(String id) {
        return dbStuMapper.selectByPrimaryKey(id);
    }
    @Override
    public List<DbStu> queryByCondition(String name, Integer sex) {
        /**
        Example example = new Example(DbStu.class);
        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo("name", name);
        criteria.andEqualTo("sex", sex);    // 只根据一个条件查询
        return dbStuMapper.selectByExample(example);
        */
        // 条件对象，和上面的Example一样
        DbStu stu = new DbStu();
        stu.setName(name);
        stu.setSex(sex);

        return dbStuMapper.select(stu);
    }
    @Override
    public void updateStu(DbStu stu) {
        dbStuMapper.updateByPrimaryKey(stu);    // 返回记录数，如果是0则表示失败
    }
    @Override
    public void deleteStu(DbStu stu) {
        // 删除对象/数据的3种方式
        // 1. 根据主键删除
        dbStuMapper.deleteByPrimaryKey(stu.getId());
        // 2. 根据对象中的属性值匹配做条件删除(用的少)
        dbStuMapper.delete(stu);
        // 3. 根据构建的Example进行条件删除
        Example example = new Example(DbStu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("name", stu.getName());
        dbStuMapper.deleteByExample(example);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void testTrans() {
        // 1.新增数据.
        // 2.修改数据
        // 3.模拟发生异常
        // 4.观察1和2步骤所发生的的数据变动，有没有影响到数据库
        // 5，处理事务，实现事务的回滚，不然先前的数据入库

        // 新增
        String sid = UUID.randomUUID().toString();
        DbStu stu = new DbStu();
        stu.setId(sid);
        stu.setName(sid);
        stu.setSex(2);
        dbStuMapper.insert(stu);
        // 模拟异常
        int a = 100 / 0;
        // 修改
        DbStu stuUpdate = new DbStu();
        stu.setId("1001");
        stu.setName("1001修改名字");
        stu.setSex(3);
        dbStuMapper.updateByPrimaryKeySelective(stuUpdate);

    }
}
